﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using com.nm;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using george.Web.Helper;

namespace com.nm.library {
	/// <summary>
	/// 二维码生成器
	/// </summary>
	public class QrCodeMaker {
		/// <summary>
		/// 生成并输出到流
		/// </summary>
		/// <param name="stream"></param>
		/// <param name="text"></param>
		/// <param name="width">单位是像素，默认100px</param>
		public static void Write(Stream stream, string text, int width = 100, QuietZoneModules quietZone= QuietZoneModules.Two) {
			var encoder = new QrEncoder(ErrorCorrectionLevel.M);
			try {
				QrCode qrCode;
				encoder.TryEncode(text, out qrCode);

				var gRenderer = new GraphicsRenderer(
					new FixedCodeSize(width, quietZone),
					//new FixedModuleSize(width, QuietZoneModules.Two),
					Brushes.Black, Brushes.White);

				gRenderer.WriteToStream(qrCode.Matrix, ImageFormat.Png, stream);
			} catch (Exception ex) {
				Log.Error(ex);
			}
		}
		/// <summary>
		/// 获取 二维码图片
		/// </summary>
		/// <param name="text"></param>
		/// <param name="width">单位：像素，默认：100px</param>
		/// <returns></returns>
		public static Image Get(string text, int width = 100,QuietZoneModules quietZone = QuietZoneModules.Two) {
			var ms = new MemoryStream();
			try {
				Write(ms, text, width, quietZone);
			}catch(Exception ex){
				Log.Error(ex);
			}
			return Image.FromStream(ms);
		}
	}
	public class QrCodeMakerHandler : IHttpHandler {
		public bool IsReusable {
			get {
				return false;
			}
		}

		public void ProcessRequest(HttpContext context) {
			var text = context.Request.Get("t", "请输入T参数");
			var width = context.Request.Get("w", 100);
			context.Response.AddHeader("Content-Type", "image/png");
			QrCodeMaker.Write(context.Response.OutputStream, text, width);
		}
	}

}
